/*
 * PanelTowerSelector.java
 *
 * Created on December 9, 2007, 2:28 PM
 * 
 * Copyright (C) 2007-2008  Hylke van der Schaaf
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3 of the License.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package hextd.UI;

import com.usoog.tdcore.exception.TileAlreadyHasTowerException;
import com.usoog.tdcore.exception.TileNotBuildableException;
import com.usoog.tdcore.gamegrid.GridPoint;
import com.usoog.tdcore.gamegrid.ScaledCanvas;
import com.usoog.tdcore.gamestate.GameState;
import com.usoog.tdcore.gamestate.GameStateDefault;
import com.usoog.tdcore.player.LocalPlayerListener;
import com.usoog.tdcore.player.Player;
import com.usoog.tdcore.player.PlayerListener;
import hextd.Constants;
import hextd.HexTD;
import hextd.core.GameManagerImplementation;
import hextd.core.GameStateImplementation;
import hextd.creep.HexTDCreep;
import hextd.creep.HexTDCreepData;
import hextd.hex.HexTile;
import hextd.hex.HexBase;
import hextd.tower.HexTDTower;
import hextd.tower.FactoryTower;
import hextd.tower.FactoryTower.type;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.geom.Point2D.Double;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JToggleButton;
import javax.swing.border.LineBorder;

/**
 *
 * @author  hylke
 */
public class PanelTowerSelector extends javax.swing.JPanel
		implements LocalPlayerListener, PlayerListener {

	private BufferedImage[] images;
	private BufferedImage[] imagesDisabled;
	private JToggleButton[] buttons;
	private String[] infoText;
	private double[] towerRanges;
	private GameManagerImplementation gameManager;
	private GameStateImplementation gameState;
	private HexTD mainApp;
	private ArrayList<FactoryTower.type> towerTypes;
	private boolean placing = false;
	private int buttonSize = 32;
	private Player<HexTDCreepData, HexTDCreep, HexTDTower> localPlayer;

	/** Creates new form PanelTowerSelector */
	public PanelTowerSelector() {
	}

	public void doInit(GameManagerImplementation gm, HexTD mainApp) {
		this.gameManager = gm;
		this.gameState = (GameStateImplementation) gm.getGameState();
		this.mainApp = mainApp;

		initComponents();
		this.towerTypes = new ArrayList<FactoryTower.type>();
		this.towerTypes.add(FactoryTower.type.greenOne);
		this.towerTypes.add(FactoryTower.type.redOne);
		this.towerTypes.add(FactoryTower.type.yellowOne);
		this.towerTypes.add(FactoryTower.type.blueOne);
		this.towerTypes.add(FactoryTower.type.firecontrol);
		this.towerTypes.add(FactoryTower.type.greenTwo);
		this.towerTypes.add(FactoryTower.type.redTwo);
		this.towerTypes.add(FactoryTower.type.yellowTwo);
		this.towerTypes.add(FactoryTower.type.blueTwo);
		this.towerTypes.add(FactoryTower.type.upgradeDamage);
		this.towerTypes.add(FactoryTower.type.greenThree);
		this.towerTypes.add(FactoryTower.type.redThree);
		this.towerTypes.add(FactoryTower.type.yellowThree);
		this.towerTypes.add(FactoryTower.type.blueThree);
		this.towerTypes.add(FactoryTower.type.upgradeRange);

		this.images = new BufferedImage[this.towerTypes.size()];
		this.imagesDisabled = new BufferedImage[this.towerTypes.size()];
		this.buttons = new JToggleButton[this.towerTypes.size()];
		this.infoText = new String[this.towerTypes.size()];
		this.towerRanges = new double[this.towerTypes.size()];

		this.makeButtons();

		GameState<HexTDCreepData, HexTDCreep, HexTDTower> tempGS = new GameStateDefault<HexTDCreepData, HexTDCreep, HexTDTower>(gm);
		ScaledCanvas sc = new ScaledCanvas() {

			private double scale;
			private float stroke;

			public double getGridPaintWidth() {
				throw new UnsupportedOperationException("Not supported yet.");
			}

			public void setGridPaintWidth(double gridPaintWidth) {
				throw new UnsupportedOperationException("Not supported yet.");
			}

			public double getPaintScale() {
				return scale;
			}

			public void setPaintScale(double scale) {
				this.scale = scale;
			}

			public float getDefaultStrokeWidth() {
				return stroke;
			}

			public void setDefaultStrokeWidth(float size) {
				this.stroke = size;
			}

			public double getOffsetX() {
				throw new UnsupportedOperationException("Not supported yet.");
			}

			public void setOffsetX(double offsetX) {
				throw new UnsupportedOperationException("Not supported yet.");
			}

			public double getOffsetY() {
				throw new UnsupportedOperationException("Not supported yet.");
			}

			public void setOffsetY(double offsetY) {
				throw new UnsupportedOperationException("Not supported yet.");
			}

			public Double fromGameToPaintCoordinates(Double source, Double target) {
				throw new UnsupportedOperationException("Not supported yet.");
			}
		};

		sc.setPaintScale(buttonSize / 2.0);
		sc.setDefaultStrokeWidth((float) sc.getPaintScale() / 40f);
		sc.setOffsetX(sc.getPaintScale() - HexTile.relativeHexWidth * sc.getPaintScale());
		sc.setOffsetY(0);

		HexTile tempHex = new HexBase(new GridPoint(0, 0), tempGS, true);
		tempHex.resetScale(sc);

		for (int i = 0; i < this.towerTypes.size(); i++) {
			this.images[i] = new BufferedImage(this.buttonSize, this.buttonSize, BufferedImage.TYPE_INT_RGB);
			this.imagesDisabled[i] = new BufferedImage(this.buttonSize, this.buttonSize, BufferedImage.TYPE_INT_RGB);
			HexTDTower tempTower;
			try {
				tempTower = FactoryTower.createTower(towerTypes.get(i), tempGS, tempHex, null, 0);
				this.infoText[i] = tempTower.getDescription();
				this.imageFromTower(this.images[i], tempHex, tempTower, false);
				this.imageFromTower(this.imagesDisabled[i], tempHex, tempTower, true);
				this.buttons[i].setIcon(new ImageIcon(this.images[i]));
				this.buttons[i].setDisabledIcon(new ImageIcon(this.imagesDisabled[i]));
				this.towerRanges[i] = tempTower.getRangeBase();
			} catch (TileAlreadyHasTowerException ex) {
				Logger.getLogger(PanelTowerSelector.class.getName()).log(Level.SEVERE, null, ex);
			} catch (TileNotBuildableException ex) {
				Logger.getLogger(PanelTowerSelector.class.getName()).log(Level.SEVERE, null, ex);
			}

		}

		gameManager.addLocalPlayerListener(this);
	}

	private void makeButtons() {
		GridBagConstraints gridBagConstraints;
		JToggleButton tempToggle;
		for (int i = 0; i < this.towerTypes.size(); i++) {
			tempToggle = new JToggleButton();
			tempToggle.setBorder(new LineBorder(Constants.colorForeGroundPale));
			tempToggle.setBackground(Constants.colorBackGround);
			tempToggle.setForeground(Constants.colorForeGround);
			this.buttons[i] = tempToggle;
			tempToggle.setMargin(new java.awt.Insets(1, 1, 1, 1));
			final int n = i;
			tempToggle.addActionListener(new java.awt.event.ActionListener() {

				@Override
				public void actionPerformed(java.awt.event.ActionEvent evt) {
					doPlace(n);
				}
			});
			tempToggle.addMouseListener(new java.awt.event.MouseAdapter() {

				@Override
				public void mouseEntered(java.awt.event.MouseEvent evt) {
					mouseOver(n);
				}
			});
			gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.gridx = n % 5;
			gridBagConstraints.gridy = n / 5;
			//gridBagConstraints.weightx = 0.01;
			//gridBagConstraints.weighty = 0.01;
			gridBagConstraints.insets = new Insets(2, 2, 2, 2);
			add(tempToggle, gridBagConstraints);
		}
	}

	private void imageFromTower(BufferedImage i, HexTile h, HexTDTower t, boolean disabled) {
		Graphics2D g2 = i.createGraphics();
		g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
		h.paint(g2, 0);
		t.paint(g2, 0);
		g2.setColor(new Color(0, 0, 0, 192));
		if (disabled) {
			g2.fillRect(0, 0, i.getWidth(), i.getHeight());
		}
		g2.dispose();
	}

	public void startPlacing(FactoryTower.type t, double r) {
		placing = true;
		mainApp.startPlacing(t, r);
	}

	public void stopPlacing() {
		this.untoggleAll();
		this.placing = false;
	}

	/**
	 * Set the tower-buy-buttons to the correct ones.
	 */
	public void mapChanged() {
		for (int i = 0; i < buttons.length; i++) {
			type ttype = towerTypes.get(i);
			buttons[i].setVisible(gameState.newTowerAllowed(ttype, localPlayer));
		}
	}

	@Override
	public void resourcesChanged() {
		for (int i = 0; i < buttons.length; i++) {
			if (buttons[i].isVisible()) {
				type ttype = towerTypes.get(i);
				buttons[i].setEnabled(localPlayer.getResources().canQueue(ttype.price));
			}
		}
	}

	@Override
	public void livesChanged(int newLives) {
	}

	@Override
	public void localPlayerChanged(Player newLocalPlayer) {
		localPlayer.removePlayerListener(this);
		localPlayer = newLocalPlayer;
		localPlayer.addPlayerListener(this);
	}

	private void untoggleAll() {
		for (int i = 0; i < this.buttons.length; i++) {
			this.buttons[i].setSelected(false);
		}
	}

	public void doPlace(int i) {
		type ttype = towerTypes.get(i);
		if (gameState.newTowerAllowed(ttype, localPlayer)) {
			mouseOver(i);
			untoggleAll();
			buttons[i].setSelected(true);
			mainApp.setInfoText(infoText[i], true);
			startPlacing(towerTypes.get(i), towerRanges[i]);
		}
	}

	private void mouseOver(int i) {
		if (!placing) {
			mainApp.setInfoText(this.infoText[i], false);
		}
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        setBackground(Constants.colorBackGround);
        setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Towers", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 12), Constants.colorForeGround)); // NOI18N
        setForeground(Constants.colorForeGround);
        setLayout(new java.awt.GridBagLayout());
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}
